<template>
	<view class="page">
		<view class="form-container">
			<!-- 表单项 -->
			<view class="form-item">
				<text class="label">
					<text class="required-star">*</text>收货人
				</text>
				<input class="input" type="text" v-model="formData.name" placeholder="请输入收货人姓名" />
			</view>

			<view class="form-item">
				<text class="label">
					<text class="required-star">*</text>手机号码
				</text>
				<input class="input" type="number" v-model="formData.phone" placeholder="请输入手机号码" maxlength="11" />
			</view>

			<view class="form-item">
				<text class="label">
					<text class="required-star">*</text>所在地区
				</text>
				<view class="input region-area" @tap="openRegionPicker">
					<text :class="['region-text', formData.region ? '' : 'placeholder']">
						{{ formData.region || '请选择所在地区' }}
					</text>
					<image class="right-arrow" src="/static/svg/right-arrow.svg" mode="aspectFit"></image>
				</view>
			</view>

			<view class="form-item">
				<text class="label">
					<text class="required-star">*</text>详细地址
				</text>
				<textarea class="textarea" v-model="formData.address" placeholder="请输入详细地址信息，如街道、门牌号等" />
			</view>

			<view class="form-item default-switch">
				<text class="label">设为默认地址</text>
				<switch :checked="formData.isDefault" @change="onDefaultChange" color="#ff6b35" />
			</view>
		</view>

		<!-- 底部保存按钮 -->
		<view class="btn-container">
			<button class="btn-save" @tap="handleSave">保存</button>
			<button v-if="isEdit" class="btn-delete" @tap="handleDelete">删除</button>
		</view>

		<!-- 添加地区选择器组件 -->
		<region-picker ref="regionPicker" :value="formData.region" @confirm="onRegionConfirm" />
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import RegionPicker from '../../../components/RegionPicker.vue';
import {one} from "../../../common/data";

// 是否是编辑模式
const isEdit = ref(false);
// 编辑的地址ID
const editId = ref(-1);

// 表单数据
const formData = reactive({
	name: '',
	phone: '',
	region: '',
	address: '',
	isDefault: false
});

// 页面加载
onLoad((options) => {
	// 如果有id参数，说明是编辑模式
	if (options.id !== undefined) {
		editId.value = Number(options.id);
		isEdit.value = true;
		loadAddressData(editId.value);
	}
});

// 加载地址数据
const loadAddressData = async (id) => {
  try {
    const res = await one("address_view", {id: id})
    if (res.code===200) {
        // 将地址数据填充到表单
        Object.assign(formData,res.data);
    }
  } catch (e) {
    console.error('加载地址数据失败', e);
  }
};

// 设为默认地址
const onDefaultChange = (e) => {
	formData.isDefault = e.detail.value;
};

// 显示地区选择器
const regionPicker = ref(null);
const openRegionPicker = () => {
	regionPicker.value.open();
};

// 地区选择确认
const onRegionConfirm = (data) => {
	formData.region = data.region;
};

// 保存地址
const handleSave = () => {
	// 表单验证
	if (!formData.name) {
		return uni.showToast({
			title: '请输入收货人姓名',
			icon: 'none'
		});
	}

	if (!formData.phone) {
		return uni.showToast({
			title: '请输入手机号码',
			icon: 'none'
		});
	}

	// 简单的手机号验证
	if (!/^1\d{10}$/.test(formData.phone)) {
		return uni.showToast({
			title: '请输入正确的手机号码',
			icon: 'none'
		});
	}

	if (!formData.region) {
		return uni.showToast({
			title: '请选择所在地区',
			icon: 'none'
		});
	}

	if (!formData.address) {
		return uni.showToast({
			title: '请输入详细地址',
			icon: 'none'
		});
	}

	// 保存地址数据
	saveAddressData();
};

// 保存地址数据
const saveAddressData = async () => {
  try {
    let res;
    
    if (isEdit.value) {
      // 编辑模式，调用更新接口
      res = await data("fn_address_update", {
        id: editId.value,
        ...formData
      });
    } else {
      // 新增模式，调用新增接口
      res = await data("fn_address_add", formData);
    }
    
    if (res.code !== 200) {
      uni.showModal({
        showCancel: false,
        content: res.msg
      });
      return;
    }

    // 提示保存成功
    uni.showToast({
      title: '保存成功',
      icon: 'success',
      success: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    });
  } catch (e) {
    console.error('保存地址数据失败', e);
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    });
  }
};

// 删除地址
const handleDelete = () => {
	uni.showModal({
		title: '提示',
		content: '确定要删除该地址吗？',
		success: (res) => {
			if (res.confirm) {
				deleteAddress();
			}
		}
	});
};

// 删除地址
const deleteAddress = () => {
	try {
		// 获取现有地址列表
		const storageData = uni.getStorageSync('addressList');
		if (storageData) {
			let addressList = JSON.parse(storageData);

			// 删除对应的地址
			addressList.splice(editId.value, 1);

			// 如果删除的是默认地址，且还有其他地址，则将第一个设为默认
			if (formData.isDefault && addressList.length > 0) {
				addressList[0].isDefault = true;
			}

			// 保存到本地存储
			uni.setStorageSync('addressList', JSON.stringify(addressList));

			// 提示删除成功
			uni.showToast({
				title: '删除成功',
				icon: 'success',
				success: () => {
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}
			});
		}
	} catch (e) {
		console.error('删除地址失败', e);
		uni.showToast({
			title: '删除失败，请重试',
			icon: 'none'
		});
	}
};
</script>

<style>
.page {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 180rpx;
}

.form-container {
	background-color: #fff;
	padding: 0 30rpx;
	margin-top: 20rpx;
}

.form-item {
	padding: 30rpx 0;
	border-bottom: 1px solid #f0f0f0;
}

.form-item:last-child {
	border-bottom: none;
}

.label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 20rpx;
	display: block;
}

.required-star {
	color: #ff4757;
	margin-right: 8rpx;
}

.input {
	font-size: 28rpx;
	color: #333;
	width: 100%;
	height: 60rpx;
}

.textarea {
	font-size: 28rpx;
	color: #333;
	width: 100%;
	height: 180rpx;
}

.placeholder {
	color: #999;
}

.region-area {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.region-text {
	flex: 1;
}

.right-arrow {
	width: 32rpx;
	height: 32rpx;
}

.default-switch {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.default-switch .label {
	margin-bottom: 0;
}

.btn-container {
	position: fixed;
	bottom: 30rpx;
	left: 0;
	width: 100%;
	padding: 0 30rpx;
	box-sizing: border-box;
}

.btn-save {
	background-color: #ff6b35;
	color: #fff;
	border-radius: 50rpx;
	height: 90rpx;
	line-height: 90rpx;
	font-size: 32rpx;
	border: none;
	margin-bottom: 20rpx;
}

.btn-delete {
	background-color: #fff;
	color: #999;
	border-radius: 50rpx;
	height: 90rpx;
	line-height: 90rpx;
	font-size: 32rpx;
	border: 1px solid #ddd;
}
</style>
